package cn.org.eshow.service.impl;

import cn.org.eshow.bean.query.MoneyQuery;
import cn.org.eshow.bean.query.RechargeQuery;
import cn.org.eshow.common.ShopDataVar;
import cn.org.eshow.common.page.Page;
import cn.org.eshow.dao.RechargeDao;
import cn.org.eshow.model.Finance;
import cn.org.eshow.model.Money;
import cn.org.eshow.model.Recharge;
import cn.org.eshow.service.BillManager;
import cn.org.eshow.service.FinanceManager;
import cn.org.eshow.service.MoneyManager;
import cn.org.eshow.service.RechargeManager;
import com.pingplusplus.model.Charge;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.WebService;
import java.util.Date;
import java.util.List;

//import static com.sun.tools.doclets.formats.html.markup.HtmlStyle.title;

@WebService(serviceName = "RechargeManager", endpointInterface = "cn.org.eshow.service.RechargeManager")
@Service
public class RechargeManagerImpl extends GenericManagerImpl<Recharge, Integer> implements RechargeManager {

    @Autowired
    private RechargeDao rechargeDao;
    @Autowired
    private MoneyManager moneyManager;
    @Autowired
    private BillManager billManager;

    @Autowired
    public RechargeManagerImpl(RechargeDao rechargeDao) {
        super(rechargeDao);
        this.rechargeDao = rechargeDao;
    }

    public RechargeManagerImpl() {
    }

    @Override
    public Page<Recharge> search(RechargeQuery query) {
        return rechargeDao.search(query);
    }

    @Override
    public List<Recharge> list(RechargeQuery query) {
        return rechargeDao.list(query);
    }


    @Override
    public Recharge check(RechargeQuery query) {
        List<Recharge> recharges = list(query);
        if (recharges.isEmpty()) {
            return null;
        }
        return recharges.get(0);
    }

    @Override
    public long count(RechargeQuery query) {
        return rechargeDao.count(query);
    }

    @Override
    public synchronized void pay(Charge charge) {
        RechargeQuery rechargeQuery = new RechargeQuery();
        rechargeQuery.setNo(charge.getOrderNo().trim());
        rechargeQuery.setState(0);
        Recharge recharge = check(rechargeQuery);
        if(recharge != null){
            recharge.setUpdateTime(new Date());
            recharge.setState(1);
            recharge.setCallback(charge.getId());
            recharge=rechargeDao.save(recharge);
            MoneyQuery moneyQuery = new MoneyQuery(true, recharge.getUser().getId());
            Money myMoney = moneyManager.check(moneyQuery);
            if (myMoney == null) {
                myMoney = moneyManager.mine(recharge.getUser());
            }
            myMoney = moneyManager.balance(myMoney,recharge.getPrice());

            billManager.calc(recharge.getUser(), ShopDataVar.billCategory.用户.toString(), ShopDataVar.billType.充值.toString(),recharge.getPrice(),0.0,myMoney.getBalance(),"recharge",recharge.getNo(),"",1,"");
        }
    }
}
